<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\WorkOrderRequest;
use App\Models\HelpWorkOrder;
use Illuminate\Http\Request;

class HelpOrdersController extends Controller
{
    public function updateOrCreate(WorkOrderRequest $request)
    {
        $data = $request->only([
            'object_id',
            'object_type',
            'content',
            'images',
        ]);

        $data['object_type'] = 'App\Models\\' . ucfirst(strtolower($data['object_type']));
        $data['user_id'] = $this->user->id;
        $data['role'] = 'user';
        $data['p_id'] = 0;

        $work_order_model = new HelpWorkOrder();

        //判断工单是否重复
        $work_order = $work_order_model->where(array_except($data, 'images'))->where('is_close', 0)->first();

        if ($work_order) {
            $this->response->error(trans('api.save_failed') . ',' . trans('api.work_order') . trans('api.exists'), 200);
        }

        //判断对象是否存在
        $model = new $data['object_type']();

        $object = $model->find($data['object_id']);

        if (!$object) {
            $this->response->error(trans('api.save_failed') . ',' . ' object ' . trans('api.not_exists'), 200);
        }

        $work_order_model->fill($data);

        $res = $work_order_model->save();

        if ($res) {
            return response()->json(['message' => trans('api.save_succeed'), 'code' => 1, 'status' => true, 'data' => ''], 200);
        } else {
            return response()->json(['message' => trans('api.save_failed'), 'code' => 0, 'status' => false], 200);
        }
    }
}
